package mc

import (
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zhtrans "github.com/go-playground/validator/v10/translations/zh"
	"strings"
)

var (
	Trans                  ut.Translator       // 翻译器
	Validate               *validator.Validate // 验证器
)

// 自定义数据验证
type Validation struct {
	Tag    string
	Func   validator.Func
	ErrMsg string
}

func ValidateErrToTrans(err error) string {
	msg := make([]string,0)
	for _, err := range err.(validator.ValidationErrors) {
		msg = append(msg, err.Translate(Trans))
	}
	return strings.Join(msg, ",")
}

func initValidate(){
	// 翻译器
	Trans, _ = ut.New(zh.New()).GetTranslator("zh")
	// 验证器
	Validate, _ = binding.Validator.Engine().(*validator.Validate)
	// 注册翻译器
	_ = zhtrans.RegisterDefaultTranslations(Validate, Trans)
}

// 注册自定义数据验证
func SetValidations(validations []Validation) {
	//注册自定义规则
	for _, validation := range validations {
		//注册验证函数
		if err := Validate.RegisterValidation(validation.Tag, validation.Func); err != nil {
			panic(ErrorInternalServerError.Copy("自定义数据验证方法 %s 注册失败：%s", validation.Tag, err.Error()))
		}
		//根据提供的标记注册翻译
		if err := Validate.RegisterTranslation(
			validation.Tag,
			Trans,
			func(ut ut.Translator) error {
				return ut.Add(validation.Tag, validation.ErrMsg, true)
			},
			func(ut ut.Translator, fe validator.FieldError) string {
				t, _ := ut.T(validation.Tag, fe.Field(), fe.Field())
				return t
			},
		); err != nil {
			panic(ErrorInternalServerError.Copy("自定义数据验证方法 %s 错误消息注册失败：%s", validation.Tag, err.Error()))
		}
	}

}
